/**
 * Created by Ng on 2023/11/09
 */

/////////
/**
 * @description 是否 String
 * @param {Any} value
 * @returns {Boolean}
 */
export function isString(value) {
  if (typeof value === 'string' || value instanceof String) {
    return true
  }
  return false
}

/**
 * @description 是否有效值
 * @param {Any} value
 * @returns {Boolean}
 */
export function isHave(value) {
  if (value === 'undefined' || value === null || value.trim() === '') {
    return false
  }
  return true
}

/////////
/**
 * @description 洗牌算法-数组乱序
 * @param {Array} ary
 * @returns {Array}
 */
export function shuffle(ary){
  // return ary.sort((n,m) => Math.random() - .5)
  let length = ary.length
  let index, temp
  while(length > 0){
    index = Math.floor(Math.random() * length)
    temp = ary[length - 1]
    ary[length - 1] = ary[index]
    ary[index] = temp
    length--
  }
  return ary
}

/////////
/**
 * @description 10 位时间戳转换
 * @param {Number} time
 * @returns {String}
 */
export function timestamp(time) {
  let date = new Date(time * 1000)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? `${m}` : m
  let d = date.getDate()
  d = d < 10 ? `${d}` : d
  let h = date.getHours()
  h = h < 10 ? `0${h}` : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? `0${minute}` : minute
  second = second < 10 ? `0${second}` : second
  return `${y}年${m}月${d}日 ${h}:${minute}:${second}`
}

/**
 * @description 格式化时间
 * @param {Number} time
 * @param {String} option
 * @returns {String}
 */
export function formatTime(time, option) {
  if (`${time}`.length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }

  let d = new Date(time)
  let now = Date.now()
  let diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return `${Math.ceil(diff / 60)}分钟前`
  } else if (diff < 3600 * 24) {
    return `${Math.ceil(diff / 3600)}小时前`
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return `${d.getMonth() + 1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分`
  }
}

/**
 * @description 格式化时间
 * @param {Number} time
 * @param {String} cFormat
 * @returns {String | Null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  let format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = `0${value}`
    }
    return value || 0
  })
  return time_str
}

/////////
/**
 * @description 手机号中间四位变成 *
 * @param {String} tel 
 * @returns {String}
 */
export function telFormat(tel) {
  tel = String(tel)
  return tel.slice(0, 3) + '****' + tel.slice(7)
}

/////////
/**
 * @description 将 url 请求参数转为 json 格式
 * @param {String} url
 * @returns {{} | Any}
 */
export function paramsToJson(url) {
  let search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(`{"${decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ')}"}`)
}

/**
 * @description 对象转 url 请求参数
 * @param {Object} params
 * @returns {String | Null}
 */
export function convertToUrl(params) {
  if (!params) {
    return null
  }
  let paramsList = []
  for (let key in params) {
    paramsList.push(key + '=' + params[key])
  }
  return '?' + paramsList.join('&')
}

/////////
/**
 * @description 数字千分位分割
 * @param {Number} value 
 * @returns {String}
 */
export function thousands(value) {
  let number = value.toString()
  let length = number.length
  if (length <= 3) {
    return value
  }
  let temp = ''
  let remainder = length % 3
  let regular = /\d{3}/g
  if (remainder > 0) {
    // 不是 3 的整数
    return number.slice(0, remainder) + ',' + number.slice(remainder, length).match(regular).join(',') + temp
  } else {
    return number.slice(0, length).match(regular).join(',') + temp
  }
}

/**
 * @description 生成随机数
 * @returns {String}
 */
export function random() {
  let number = ''
  for (let index = 0; index < 6; index++) {
    number += Math.floor(Math.random() * 10)
  }
  return number
}

/**
 * @description 生成 min - max 的随机数
 * @param {Number} min
 * @param {Number} max
 * @returns {Number}
 */
export function randomMN(min, max) {
  // let number = Math.floor(Math.random() * (max - min) + min)
  let number = Math.floor(Math.random() * (max - min + 1) + min)
  return number
}

/**
 * @description 生成随机 ID
 * @param {Number} length
 * @returns {String}
 */
export function uuid(length = 32) {
  let uuid = ''
  let num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  for (let index = 0; index < length.length; index++) {
    uuid += num.charAt(Math.floor(Math.random() * num.length))
  }
  return uuid
}

/////////
/**
 * @description 是否移动端
 * @returns {Boolean}
 */
export function isMobile() {
  let userAgent = navigator.userAgent.toLowerCase()
  let isPhone = /AppleWebKit.*Mobile/i.test(navigator.userAgent)
  let isPad = userAgent.match(/ipad/i) !== null
  let isPhoneOS = userAgent.match(/iphone os/i) !== null
  let isMidp = userAgent.match(/midp/i) !== null
  let isRV = userAgent.match(/rv:1.2.3.4/i) !== null
  let isUC = userAgent.match(/ucbrowser/i) !== null
  let isAndroid = userAgent.match(/android/i) !== null
  let isWindowsCE = userAgent.match(/windows ce/i) !== null
  let isWindowsMobile = userAgent.match(/windows mobile/i) !== null
  if (isPhone || isPad || isPhoneOS || isMidp || isRV || isUC || isAndroid || isWindowsCE || isWindowsMobile) {
    return true
  }
  return false
}

/////////
/**
 * @description 获取浏览器型号及版本信息
 * @returns {Object}
 */
export function browserInfo() {
  let agent = navigator.userAgent.toLowerCase()
  // IE < 11
  if (agent.indexOf('msie') >= 0) {
    return {type: 'IE', version: Number(agent.match(/msie ([\d]+)/)[1])}
  }
  // IE 11
  if (agent.match(/trident\/.+?rv:(([\d.]+))/)) {
    return {type: 'IE', version: 11}
  }
  if (agent.indexOf('edge') >= 0) {
    return {type: 'Edge', version: Number(agent.match(/edge\/([\d]+)/)[1])}
  }
  if (agent.indexOf('firefox') >= 0) {
    return {type: 'Firefox', version: Number(agent.match(/firefox\/([\d]+)/)[1])}
  }
  if (agent.indexOf('chrome') >= 0) {
    return {type: 'Chrome', version: Number(agent.match(/chrome\/([\d]+)/)[1])}
  }
  if (agent.indexOf('opera') >= 0) {
    return {type: 'Opera', version: Number(agent.match(/opera.([\d]+)/)[1])}
  }
  if (agent.indexOf('Safari') >= 0) {
    return {type: 'Safari', version: Number(agent.match(/version\/([\d]+)/)[1])}
  }
  return {type: agent, version: -1}
}

/**
 * @description 滚动条回到顶部动画
 */
export function scrollToTop() {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, scrollTop - scrollTop / 8)
  } else {
    window.cancelAnimationFrame(scrollToTop)
  }
}
